package com.novellotus.iov.carvice.activity;

import android.Manifest;
import android.content.Context;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ljd.retrofit.progress.ProgressHelper;
import com.novellotus.httploadingview.LoadingView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.adapter.HomePageEnterpriseAdapter;
import com.novellotus.iov.carvice.adapter.MainPagerAdapter;
import com.novellotus.iov.carvice.bean.RxEinfos;
import com.novellotus.iov.carvice.bean.RxUpdate;
import com.novellotus.iov.carvice.contract.MainActivityContract;
import com.novellotus.iov.carvice.fragment.HomePagerFragment;
import com.novellotus.iov.carvice.fragment.MineFragment;
import com.novellotus.iov.carvice.fragment.WorkFragment;
import com.novellotus.iov.carvice.presenter.MainActivityPresenter;
import com.novellotus.iov.carvice.retrofit.BaseArrayEntity;
import com.novellotus.iov.carvice.retrofit.BaseArrayObserver;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.HandlerUtils;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.TipsDialog;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class MainActivity extends BaseActivity implements MainActivityContract.View, HomePageEnterpriseAdapter.EnterpriseClickInterface, TipsDialog.ClickTipsInterface, HandlerUtils.OnReceiveMessageListener, LoadingView.OnBtnClickListener {

    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.loadingView)
    LoadingView loadingView;

    MainActivityContract.Presenter presenter;
    MainPagerAdapter mainPagerAdapter;
    List<Fragment> fragmentList;
    List<RxEinfos> rxEinfosList;
    private HandlerUtils.HandlerHolder handlerHolder;
    //授权是否成功
    private boolean authorization = true;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
    }

    @Override
    public void init() {
        if (MyUtils.isEnglish(this)) {
            MyUtils.logInformation("英文");
        } else {
            MyUtils.logInformation("中文");
        }
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)//多个权限用","隔开
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (!aBoolean) {
                            MyUtils.showToast(MainActivity.this, "请开启本应用定位权限，否则无法定位您的位置");
                        }
                    }
                });
        loadingView.setLoadingModel(LoadingView.MODEL_ALERT);
        loadingView.setOnBtnClickListener(this);
        handlerHolder = new HandlerUtils.HandlerHolder(this);
        presenter = new MainActivityPresenter(this);
        presenter.getMainMessage();
        checkUpdate();

    }


    @Override
    public void initLayout(List<Fragment> fragmentList) {
        this.fragmentList = fragmentList;
        WorkFragment workFragment = (WorkFragment) fragmentList.get(1);
        workFragment.setActivity(this);
        mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(mainPagerAdapter);
        viewPager.setOffscreenPageLimit(4);
        tabLayout.setupWithViewPager(viewPager);
        //   getList();
    }


    @Override
    public void initTabLayout() {
        //首页
        View viewHome = View.inflate(this, R.layout.layout_item_tab, null);
        TabLayout.Tab tabHome = tabLayout.getTabAt(0);
        TextView tvHome = viewHome.findViewById(R.id.tv_tab);
        tvHome.setText(getResources().getString(R.string.home));
        if (tabHome != null) {
            tabHome.setCustomView(viewHome);
        }

        //工作
        View viewWork = View.inflate(this, R.layout.layout_item_tab, null);
        ImageView imgWork = viewWork.findViewById(R.id.img_tab);
        TextView tvWork = viewWork.findViewById(R.id.tv_tab);
        imgWork.setBackgroundResource(R.drawable.selector_work);
        tvWork.setText(getResources().getString(R.string.work));
        TabLayout.Tab tabWork = tabLayout.getTabAt(1);
        if (tabWork != null) {
            tabWork.setCustomView(viewWork);
        }

        //消息
        View viewMessage = View.inflate(this, R.layout.layout_item_tab, null);
        ImageView imgMessage = viewMessage.findViewById(R.id.img_tab);
        TextView tvMessage = viewMessage.findViewById(R.id.tv_tab);
        imgMessage.setBackgroundResource(R.drawable.selector_message);
        tvMessage.setText(getResources().getString(R.string.news));
        TabLayout.Tab tabMessage = tabLayout.getTabAt(2);
        if (tabMessage != null) {
            tabMessage.setCustomView(viewMessage);
        }
        //我的
        View viewMine = View.inflate(this, R.layout.layout_item_tab, null);
        ImageView imgMine = viewMine.findViewById(R.id.img_tab);
        TextView tvMine = viewMine.findViewById(R.id.tv_tab);
        imgMine.setBackgroundResource(R.drawable.selector_mine);
        tvMine.setText(getResources().getString(R.string.mine));
        TabLayout.Tab tabMine = tabLayout.getTabAt(3);
        if (tabMine != null) {
            tabMine.setCustomView(viewMine);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (rxEinfosList == null) {
            getList();
        }
    }

    /**
     * 获取角色列表
     */
    public void getList() {
        Observable<BaseArrayEntity<RxEinfos>> observable = RetrofitFactory.getInstance().einfos(SharedPreferencesUtils.getKey(getContext())[0]);
        observable.compose(RxSchedulers.<BaseArrayEntity<RxEinfos>>compose())
                .subscribe(new BaseArrayObserver<RxEinfos>(getContext()) {
                    @Override
                    public void onSuccess(List<RxEinfos> list) {
                        loadingView.success();
                        rxEinfosList = list;
                        HomePagerFragment homePagerFragment = (HomePagerFragment) fragmentList.get(0);
                        homePagerFragment.setCompanyList(list, MainActivity.this);
                        MineFragment mineFragment = (MineFragment) fragmentList.get(3);
                        if (list.size() != 0) {
                            mineFragment.setEnterprise(list.get(0));
                        } else {
                            mineFragment.setEnterprise(null);
                        }
                        WorkFragment workFragment = (WorkFragment) fragmentList.get(1);
                        workFragment.setEnterprise(list);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        if (code == 401) {
                            authorization = false;
                            loadingView.mLoadDataBtn.setText("重新登录");
                        }
                        loadingView.empty(msg, true);
                    }

                    @Override
                    public void onError(String msg) {
                        loadingView.setBackgroundColor(MainActivity.this.getResources().getColor(R.color.load_fail));
                        loadingView.empty("网络请求失败", true);
                    }
                });
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void clickEnterprise(RxEinfos rxEinfos, int position) {
        WorkFragment workFragment = (WorkFragment) fragmentList.get(1);
        workFragment.updateEnterprise(rxEinfos, position);
        tabLayout.getTabAt(1).select();
        MineFragment mineFragment = (MineFragment) fragmentList.get(3);
        mineFragment.setEnterprise(rxEinfos);
    }

    public void updateMineFragment(RxEinfos rxEinfos, int position) {
        MineFragment mineFragment = (MineFragment) fragmentList.get(3);
        mineFragment.setEnterprise(rxEinfosList.get(position));
    }

    /**
     * 检查是否需要更新
     */
    boolean isUpdate;
    String des = "", url = "";
    TipsDialog tipsDialog;

    public void checkUpdate() {
        Observable<BaseEntity<RxUpdate>> observable = RetrofitFactory.getInstance().updateVersion(MyUtils.getVersionCode(this), SharedPreferencesUtils.getKey(this)[0]);
        observable.compose(RxSchedulers.<BaseEntity<RxUpdate>>compose())
                .subscribe(new BaseObserver<RxUpdate>(this) {
                    @Override
                    public void onSuccess(RxUpdate response) {
                        if (response.getUpdate() == 1 || response.getUpdate() == 2) {
                            MineFragment mineFragment = (MineFragment) fragmentList.get(3);

                            isUpdate = true;
                            des = response.getAppVersionVO().getUpdateLog();
                            url = response.getAppVersionVO().getDownloadUrl();
                            mineFragment.setUpdate(url, des);
                            tipsDialog = new TipsDialog(MainActivity.this);
                            tipsDialog.initDialog("版本更新", des, MainActivity.this);
                            tipsDialog.button.setText("更新");
                            if (response.getUpdate() == 1) {
                                tipsDialog.setCancelable(false);
                                tipsDialog.img_cancel.setVisibility(View.GONE);
                            }
                            tipsDialog.show();
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                    }

                    @Override
                    public void onError(String msg) {
                    }

                });
    }

    @Override
    public void clickTipsButton() {
        if (isUpdate) {
            Observable.create(new ObservableOnSubscribe<Object>() {
                @Override
                public void subscribe(ObservableEmitter<Object> e) throws Exception {
                    e.onNext(1);
                }
            })
                    .compose(RxSchedulers.lifecycle(this))
                    .compose(rxPermissions.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)).subscribe(new Consumer<Permission>() {
                @Override
                public void accept(Permission permission) throws Exception {
                    if (permission.granted) {
                        RetrofitFactory.getDownLoadInstance(MainActivity.this, "版本更新", des).downloadFile(url)
                                .subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new MyObserver<ResponseBody>() {
                            @Override
                            public void onNext(ResponseBody responseBody) {
                                super.onNext(responseBody);
                                ProgressHelper.outPutApk(responseBody.byteStream(), MainActivity.this);
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                Message message = new Message();
                                message.what = 0;
                                message.obj = e.toString();
                                handlerHolder.sendMessage(message);
                            }
                        });
                    } else {
                        MyUtils.showToast(MainActivity.this, "读写手机存储权限被禁止，请在设置中允许相关权限");
                    }
                }
            });
        }
        tipsDialog.dismiss();
    }

    @Override
    public void handlerMessage(Message msg) {
        MyUtils.showToast(MainActivity.this, msg.obj.toString());
    }

    @Override
    public void onReload() {
        if (!authorization) {
            openActivity(LoginActivity.class);
            SharedPreferencesUtils.deleteSharedPreferences(getContext());
            finish();
        } else {
            getList();
        }
    }
}
